<template>
  <div class="order-update-page">
    <nut-form ref="formRef" :model-value="formData" :rules="rules">
      <!-- 订单基本信息 -->
      <nut-cell-group v-if="productName" title="订单信息">
        <nut-cell title="产品名称" :desc="productName" />
      </nut-cell-group>

      <!-- 客户信息 -->
      <nut-cell-group title="客户信息">
        <nut-form-item label="客户姓名" required prop="customName" :rules="[{ required: true, message: '请输入客户姓名' }]">
          <nut-input v-model="formData.customName" placeholder="请输入客户姓名" clearable />
        </nut-form-item>

        <nut-form-item label="客户手机号" required prop="customPhone" :rules="phoneRules">
          <nut-input v-model="formData.customPhone" placeholder="请输入客户手机号" type="tel" clearable />
        </nut-form-item>

        <nut-form-item label="证件类型" prop="idType">
          <nut-radio-group v-model="formData.idType" direction="horizontal">
            <nut-radio label="00">身份证</nut-radio>
            <nut-radio label="01">驾驶证</nut-radio>
          </nut-radio-group>
        </nut-form-item>

        <nut-form-item label="证件号" required prop="customIdCard" :rules="[{ required: true, message: '请输入证件号' }]">
          <nut-input v-model="formData.customIdCard" placeholder="请输入证件号" clearable />
        </nut-form-item>

        <nut-form-item label="客户邮箱" prop="customEmail">
          <nut-input v-model="formData.customEmail" placeholder="请输入客户邮箱" type="email" clearable />
        </nut-form-item>
      </nut-cell-group>

      <!-- 车辆信息 -->
      <nut-cell-group title="车辆信息">
        <nut-form-item label="车架号" required prop="vinCode" :rules="[{ required: true, message: '请输入车架号' }]">
          <nut-input v-model="formData.vinCode" placeholder="请输入车架号" clearable />
        </nut-form-item>

        <nut-form-item label="发动机号" required prop="engineNumber" :rules="[{ required: true, message: '请输入发动机号' }]">
          <nut-input v-model="formData.engineNumber" placeholder="请输入发动机号" clearable />
        </nut-form-item>

        <nut-form-item label="车牌号" prop="licensePlateNumber">
          <nut-input v-model="formData.licensePlateNumber" placeholder="请输入车牌号" clearable />
        </nut-form-item>

        <nut-form-item label="车辆类型" required prop="vehicleType" :rules="[{ required: true, message: '请输入车辆类型' }]">
          <nut-input v-model="formData.vehicleType" placeholder="请输入车辆类型" clearable />
        </nut-form-item>

        <nut-form-item label="品牌型号" required prop="model" :rules="[{ required: true, message: '请输入品牌型号' }]">
          <nut-input v-model="formData.model" placeholder="请输入品牌型号" clearable />
        </nut-form-item>

        <nut-form-item label="使用性质" required prop="useNature" :rules="[{ required: true, message: '请输入使用性质' }]">
          <nut-input v-model="formData.useNature" placeholder="请输入使用性质" clearable />
        </nut-form-item>

        <nut-form-item label="核载人数" prop="passengerCapacity">
          <nut-input v-model="formData.passengerCapacity" placeholder="请输入核载人数" type="number" clearable />
        </nut-form-item>

        <nut-form-item label="新车发票价" required prop="carPrice" :rules="amountRules">
          <nut-input v-model="formData.carPrice" placeholder="请输入新车发票价" type="number" clearable />
        </nut-form-item>

        <nut-form-item label="购车发票日期" required prop="payCarTime" :rules="[{ required: true, message: '请选择购车发票日期' }]">
          <nut-input v-model="formData.payCarTime" placeholder="请选择购车发票日期" type="date" clearable />
        </nut-form-item>

        <nut-form-item label="其他信息" prop="otherMessage">
          <nut-textarea v-model="formData.otherMessage" placeholder="请输入其他信息" :rows="3" />
        </nut-form-item>
      </nut-cell-group>

      <!-- 保险信息 -->
      <nut-cell-group :title="'保险信息'">
        <nut-form-item label="商业保险单号" prop="insuranceNo">
          <nut-input v-model="formData.insuranceNo" placeholder="请输入商业保险单号" clearable />
        </nut-form-item>

        <nut-form-item label="商业保险公司" prop="insuranceCompany">
          <nut-input v-model="formData.insuranceCompany" placeholder="请输入商业保险公司" clearable />
        </nut-form-item>

        <nut-form-item label="商业保险开始时间" prop="insuranceStartTime">
          <nut-input v-model="formData.insuranceStartTime" placeholder="请选择商业保险开始时间" type="date" clearable />
        </nut-form-item>

        <nut-form-item label="商业保险结束时间" prop="insuranceEndTime">
          <nut-input v-model="formData.insuranceEndTime" placeholder="请选择商业保险结束时间" type="date" clearable />
        </nut-form-item>
      </nut-cell-group>

      <!-- 支付信息 -->
      <nut-cell-group v-if="payInfoList && payInfoList.length > 0" title="支付信息">
        <!-- 顶部支付信息概览 -->
        <nut-cell title="产品价格" :desc="formatAmount(totalAmount)" />
        <nut-cell title="支付类型" :desc="payTypeName || '--'" />
        <nut-cell title="剩余待支付金额" :desc="formatAmount(unpaidAmount)" />
        
        <!-- 支付历史明细 -->
        <nut-cell title="支付历史明细" @click="payHistoryExpanded = !payHistoryExpanded">
          <template #desc>
            <span class="collapse-btn" :class="{ expanded: payHistoryExpanded }">
              {{ payHistoryExpanded ? '收起' : '展开' }}
            </span>
          </template>
        </nut-cell>

        <!-- 支付记录列表 -->
        <div v-if="payHistoryExpanded" class="pay-history-list">
          <div
            v-for="(payInfo, index) in payInfoList"
            :key="payInfo.payId || index"
            class="pay-history-item"
          >
            <div class="pay-history-row">
              <span class="label">支付流水号:</span>
              <span class="value">{{ payInfo.payNo || '--' }}</span>
            </div>
            <div class="pay-history-row">
              <span class="label">支付方式:</span>
              <span class="value">{{ payInfo.payMethodName || payInfo.payChannelName || '--' }}</span>
            </div>
            <div class="pay-history-row">
              <span class="label">支付金额:</span>
              <span class="value">{{ formatAmount(payInfo.paidAmount) }}</span>
            </div>
            <div class="pay-history-row">
              <span class="label">支付时间:</span>
              <span class="value">{{ payInfo.paidTime ? formatTime(payInfo.paidTime) : '--' }}</span>
            </div>
            <div class="pay-history-row">
              <span class="label">支付状态:</span>
              <nut-tag :type="getPayStatusTagType(payInfo.payStatus)">{{ payInfo.payStatusName || '--' }}</nut-tag>
            </div>
            <div class="pay-history-row">
              <span class="label">剩余待支付金额:</span>
              <span class="value">{{ formatAmount(payInfo.unpaidAmount) }}</span>
            </div>
            <div class="pay-history-footer">
              <span class="view-detail-link" @click.stop="goToPayDetail(payInfo.payId)">
                查看详情
                <component :is="ArrowRight" class="arrow-icon" />
              </span>
            </div>
          </div>
        </div>
      </nut-cell-group>

      <!-- 附件上传 -->
      <nut-cell-group title="附件">
        <div class="file-upload-section">
          <div v-for="(file, index) in fileList" :key="index" class="file-item">
            <div class="file-info">
              <span class="file-name">{{ file.name || `附件 ${index + 1}` }}</span>
              <nut-button size="small" type="danger" @click="removeFile(index)">删除</nut-button>
            </div>
            <img v-if="file.url" :src="file.url" alt="附件预览" class="file-preview" />
          </div>
          <nut-button type="primary" block @click="handleFileUpload">上传图片</nut-button>
          <input ref="fileInputRef" type="file" accept="image/*" multiple style="display: none" @change="handleFileChange" />
        </div>
      </nut-cell-group>

      <!-- 提交按钮 -->
      <div class="action-buttons">
        <nut-button type="primary" block :loading="submitting" @click="handleSubmit">修改订单</nut-button>
      </div>
    </nut-form>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { showToast } from '@nutui/nutui';
  import { ArrowRight } from '@nutui/icons-vue';
  import { fetchOrderDetail, updateOrder, type OrderDetail, type UpdateOrderPayload, type OrderPayInfo } from '@/api/order';
  import { uploadFile } from '@/api';
  import dayjs from 'dayjs';

  const router = useRouter();
  const route = useRoute();

  const formRef = ref<any>(null);
  const submitting = ref(false);
  const fileInputRef = ref<HTMLInputElement | null>(null);

  // 订单ID
  const orderId = ref('');

  // 产品名称
  const productName = ref('');

  // 订单金额信息
  const totalAmount = ref<number>(0);
  const unpaidAmount = ref<number>(0);
  const payTypeName = ref('');

  // 支付历史明细展开状态
  const payHistoryExpanded = ref(true);

  // 表单数据
  const formData = reactive<UpdateOrderPayload>({
    orderId: '',
    idType: '00',
    customName: '',
    customIdCard: '',
    customPhone: '',
    customEmail: '',
    fileList: [],
    vinCode: '',
    engineNumber: '',
    licensePlateNumber: '',
    vehicleType: '',
    model: '',
    useNature: '',
    passengerCapacity: '',
    carPrice: 0,
    payCarTime: '',
    otherMessage: '',
    insuranceNo: '',
    insuranceStartTime: '',
    insuranceEndTime: '',
    insuranceCompany: '',
  });

  // 文件列表
  const fileList = ref<Array<{ url: string; name?: string }>>([]);

  // 支付信息列表
  const payInfoList = ref<OrderPayInfo[]>([]);

  // 表单验证规则
  const phoneRules = [
    { required: true, message: '请输入客户手机号' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' },
  ];

  const amountRules = [
    { required: true, message: '请输入金额' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的金额' },
  ];

  const rules = {
    customName: [{ required: true, message: '请输入客户姓名' }],
    customPhone: phoneRules,
    customIdCard: [{ required: true, message: '请输入证件号' }],
    vinCode: [{ required: true, message: '请输入车架号' }],
    engineNumber: [{ required: true, message: '请输入发动机号' }],
    vehicleType: [{ required: true, message: '请输入车辆类型' }],
    model: [{ required: true, message: '请输入品牌型号' }],
    useNature: [{ required: true, message: '请输入使用性质' }],
    carPrice: amountRules,
    payCarTime: [{ required: true, message: '请选择购车发票日期' }],
  };

  // 加载订单详情（用于回填数据）
  const loadOrderDetail = async () => {
    const id = route.query.orderId as string;
    if (!id) {
      showToast.text('订单ID不能为空');
      router.back();
      return;
    }

    orderId.value = id;
    formData.orderId = id;

    try {
      const { code, data, msg }: any = await fetchOrderDetail(id);
      if (code !== 200) throw new Error(msg);
      
      // 回填产品名称
      productName.value = data.productName || '';
      
      // 回填订单金额信息
      totalAmount.value = data.totalAmount || 0;
      unpaidAmount.value = data.unpaidAmount || 0;
      
      // 回填已有数据
      formData.customName = data.customName || '';
      formData.customPhone = data.customPhone || '';
      formData.customIdCard = data.customIdCard || '';
      formData.customEmail = data.customEmail || '';
      formData.idType = data.idType || '00';
      formData.vinCode = data.vinCode || '';
      formData.engineNumber = data.engineNumber || '';
      formData.licensePlateNumber = data.licensePlateNumber || '';
      formData.vehicleType = data.vehicleType || '';
      formData.model = data.model || '';
      formData.useNature = data.useNature || '';
      formData.passengerCapacity = data.passengerCapacity || '';
      formData.carPrice = data.carPrice || 0;
      formData.payCarTime = data.payCarTime || '';
      formData.otherMessage = data.otherMessage || '';
      formData.insuranceNo = data.insuranceNo || '';
      formData.insuranceStartTime = data.insuranceStartTime || '';
      formData.insuranceEndTime = data.insuranceEndTime || '';
      formData.insuranceCompany = data.insuranceCompany || '';

      // 回填附件
      if (data.fileList && data.fileList.length > 0) {
        fileList.value = data.fileList.map((url: string) => ({ url }));
        formData.fileList = data.fileList;
      }

      // 回填支付信息
      if (data.payInfoList && data.payInfoList.length > 0) {
        payInfoList.value = data.payInfoList;
        // 从第一条支付记录中获取支付类型
        if (data.payInfoList[0]?.payTypeName) {
          payTypeName.value = data.payInfoList[0].payTypeName;
        }
      }
    } catch (error: any) {
      console.error('获取订单详情失败', error);
      showToast.text(error?.message || '获取订单详情失败');
    }
  };

  // 文件上传
  const handleFileUpload = () => {
    fileInputRef.value?.click();
  };

  const handleFileChange = async (event: Event) => {
    const target = event.target as HTMLInputElement;
    const files = target.files;
    if (!files || files.length === 0) return;

    for (const file of Array.from(files)) {
      // 验证文件类型
      if (!file.type.startsWith('image/')) {
        showToast.text('请选择图片文件');
        continue;
      }

      // 验证文件大小（限制 5MB）
      if (file.size > 5 * 1024 * 1024) {
        showToast.text('图片大小不能超过 5MB');
        continue;
      }

      try {
        const result = await uploadFile(file);
        if (result?.url) {
          fileList.value.push({ url: result.url, name: file.name });
          formData.fileList = fileList.value.map((item) => item.url);
        } else {
          showToast.text('图片上传失败');
        }
      } catch (error: any) {
        console.error('图片上传失败', error);
        showToast.text(error?.message || '图片上传失败');
      }
    }

    // 清空 input，以便可以重复选择同一文件
    if (target) {
      target.value = '';
    }
  };

  const removeFile = (index: number) => {
    fileList.value.splice(index, 1);
    formData.fileList = fileList.value.map((item) => item.url);
  };

  // 格式化金额
  const formatAmount = (amount?: number) => {
    if (amount === undefined || amount === null) return '--';
    return `¥${amount.toFixed(2)}`;
  };

  // 格式化时间
  const formatTime = (time?: string) => {
    if (!time) return '--';
    return dayjs(time).format('YYYY-MM-DD HH:mm:ss');
  };

  // 获取支付状态标签类型
  const getPayStatusTagType = (status?: string) => {
    switch (status) {
      case '00':
        return 'warning';
      case '01':
        return 'success';
      case '02':
        return 'danger';
      default:
        return 'default';
    }
  };

  // 跳转到支付详情页
  const goToPayDetail = (payId?: string) => {
    if (!payId) return;
    router.push({
      path: '/order/pay',
      query: { payId },
    });
  };

  // 提交
  const handleSubmit = async () => {
    formRef.value?.validate().then(async ({ valid, errors }: any) => {
      if (!valid) {
        console.warn(errors);
        return;
      }

      try {
        submitting.value = true;

        const payload: UpdateOrderPayload = {
          ...formData,
          carPrice: Number(formData.carPrice),
        };

        await updateOrder(payload);
        showToast.text('修改成功');
        router.back();
      } catch (error: any) {
        console.error('修改失败', error);
        showToast.text(error?.message || '修改失败');
      } finally {
        submitting.value = false;
      }
    });
  };

  // 初始化
  onMounted(() => {
    loadOrderDetail();
  });
</script>

<style lang="scss" scoped>
  .order-update-page {
    min-height: 100vh;
    background-color: #f5f5f5;
    padding-bottom: 20px;
  }

  .file-upload-section {
    padding: 20px;

    .file-item {
      margin-bottom: 20px;
      padding: 15px;
      background-color: #fff;
      border-radius: 8px;

      .file-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;

        .file-name {
          font-size: 28px;
          color: #333;
        }
      }

      .file-preview {
        width: 100%;
        max-height: 400px;
        border-radius: 8px;
        object-fit: contain;
      }
    }
  }

  .action-buttons {
    padding: 20px;
    margin-top: 20px;
  }

  .pay-info-section {
    margin-bottom: 10px;

    .pay-info-content {
      .pay-info-row {
        display: flex;
        margin-bottom: 8px;
        font-size: 24px;
        align-items: center;

        .label {
          color: #666;
          margin-right: 10px;
          min-width: 140px;
        }

        .value {
          color: #333;
          flex: 1;
        }
      }
    }
  }

  .collapse-btn {
    color: #ff3b30;
    font-size: 24px;
    cursor: pointer;

    &.expanded::after {
      content: '▼';
      margin-left: 4px;
    }

    &:not(.expanded)::after {
      content: '▲';
      margin-left: 4px;
    }
  }

  .pay-history-list {
    padding: 0 16px 16px;
    background-color: #fafafa;

    .pay-history-item {
      background-color: #fff;
      border-radius: 8px;
      padding: 16px;
      margin-bottom: 12px;

      .pay-history-row {
        display: flex;
        margin-bottom: 8px;
        font-size: 24px;
        align-items: center;

        .label {
          color: #666;
          margin-right: 10px;
          min-width: 140px;
        }

        .value {
          color: #333;
          flex: 1;
        }
      }

      .pay-history-footer {
        margin-top: 12px;
        padding-top: 12px;
        border-top: 1px solid #f0f0f0;
        text-align: right;

        .view-detail-link {
          color: #ff3b30;
          font-size: 24px;
          cursor: pointer;
          display: inline-flex;
          align-items: center;
          gap: 4px;

          .arrow-icon {
            width: 16px;
            height: 16px;
            font-size: 16px;
          }

          &:hover {
            text-decoration: underline;
          }
        }
      }
    }
  }
</style>
